<!--健康档案队列-->
<template>
  <div class="p-2">
    <el-row>
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="120px">
            <el-form-item label="签约机构：" prop="documentationUnit">
              <el-tree-select
                v-model="form.documentationUnit"
                ref="deptTreeRef"
                node-key="id"
                :data="deptOptions"
                :props="{ value: 'id',label: 'label', children: 'children' }"

                :filter-node-method="filterNode"
                highlight-current
                @node-click="handleNodeClick"

                check-strictly
                @change="handleDeptChange"
                clearable
                filterable
                :filter-method="filterNode"
              />
            </el-form-item>
            <el-form-item label="签约团队：" prop="unanimous">
              <el-select v-model="queryParams.unanimous" placeholder="请选择" clearable
                         @keyup.enter="handleQuery">
              </el-select>
            </el-form-item>
            <el-form-item label="责任医生：" prop="unanimous">
              <el-select v-model="queryParams.unanimous" placeholder="请选择" clearable
                         @keyup.enter="handleQuery">
              </el-select>
            </el-form-item>
            <el-form-item label="签约状态：" prop="range">
              <el-select v-model="queryParams.range" placeholder="请选择" clearable
                         @keyup.enter="handleQuery">
                <el-option label="签约过期不超过一个月" :value="true"></el-option>
                <el-option label="签约过期" :value="false"></el-option>
                <el-option label="签约即将过期" :value="false"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="居民姓名：" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable
                        @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="身份证号：" prop="idCard">
              <el-input v-model="queryParams.idCard" placeholder="请输入身份证号" clearable
                        @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <el-card shadow="hover">
        <el-table v-loading="loading" :data="patientInfoList" @selection-change="handleSelectionChange">
          <el-table-column label="姓名" align="center" prop="name" />
          <el-table-column label="身份证号" align="center" prop="idCard" width="200" />
          <el-table-column label="人群类型" align="center" prop="queueInfo" width="300">
            <template #default="scope">
              <dict-tag :options="bp_pt_sign" :value="scope.row.queueInfo" />
            </template>
          </el-table-column>
          <el-table-column label="性别" align="center" prop="gender">
            <template #default="scope">
              <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
            </template>
          </el-table-column>
          <el-table-column label="年龄" align="center" prop="age" width="100" />
          <!--            <el-table-column label="联系方式" align="center" prop="contactPersonInfo" width="200">-->
          <!--              <template #default="scope">-->
          <!--                {{ scope.row.contactPersonInfo ? scope.row.contactPersonInfo[0].phone : "" }}-->
          <!--              </template>-->
          <!--            </el-table-column>-->
          <el-table-column label="个人电话" align="center" prop="personalPhone" width="200" />

          <el-table-column label="健康建档" align="center" prop="documentationUnitName" width="250" />
          <el-table-column label="签约" align="center" prop="signDoctor" width="200" />
          <el-table-column label="最近一次诊疗" align="center" prop="lastVisit" width="320" />

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
            <template #default="scope">
              <el-tooltip content="查看" placement="top">
                <el-button link type="primary" icon="View" @click="handleLook(scope.row)"
                           v-hasPermi="['basicPublic:patientInfo:edit']"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-card>
      <!-- </el-col>-->
    </el-row>
    <!-- 添加或修改患者基本信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" center width="1200px" append-to-body>
      <el-form ref="patientInfoFormRef" :model="form" :rules="rules" :inline="true" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="form.idCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.id">
            <el-form-item label="档案号" prop="archiveNumber">
              <el-input v-model="form.archiveNumber" placeholder="请输入档案号" />
            </el-form-item>
          </el-col>

          <el-col :span="8" v-if="form.id">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="form.gender">
                <el-radio
                  v-for="dict in sys_user_sex"
                  :key="dict.value"
                  :value="dict.value"
                  :label="dict.label"
                >
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="8" v-if="form.id">
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker
                clearable
                v-model="form.birthday"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择出生日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="个人电话" prop="personalPhone">
              <el-input v-model="form.personalPhone" placeholder="请输入个人电话" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="婚姻状况" prop="maritalStatus">
              <el-radio-group v-model="form.maritalStatus">
                <el-radio
                  v-for="dict in bp_marital_status"
                  :key="dict.value"
                  :value="dict.value"
                  :label="dict.label"
                >
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.id">
            <el-form-item label="建档单位" prop="documentationUnit" v-if="form.id">
              <el-tree-select
                v-model="form.documentationUnit"
                :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="请选择建档单位"
                check-strictly
                @change="handleDeptChange"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.id">
            <el-form-item label="责任医生" prop="dutyDoctor" v-if="form.id">
              <el-select v-model="form.dutyDoctor" placeholder="请选择责任医生" clearable>
                <el-option
                  v-for="dict in doctorDictListForm"
                  :key="dict.userId"
                  :label="dict.nickName"
                  :value="String(dict.userId)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.id">
            <el-form-item label="建档人" prop="documentationPeople" v-if="form.id">
              <el-select v-model="form.documentationPeople" placeholder="请选择建档人" clearable>
                <el-option
                  v-for="dict in doctorDictListForm"
                  :key="dict.userId"
                  :label="dict.nickName"
                  :value="String(dict.userId)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.id">
            <el-form-item label="建档日期" prop="documentationTime" v-if="form.id">
              <el-date-picker
                clearable
                v-model="form.documentationTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择建档日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人" prop="contactPersonInfoRelation">
              <el-select v-model="form.contactPersonInfoRelation" placeholder="请选择关系" style="width: 120px"
                         clearable>
                <el-option
                  v-for="dict in bp_contacts_relationship"
                  :key="dict.value"
                  :value="dict.value"
                  :label="dict.label"
                ></el-option>
              </el-select>
              <el-input v-model="form.contactPersonInfoName" placeholder="联系人姓名" style="width: 120px" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人电话" prop="contactPersonInfoPhone">
              <el-input v-model="form.contactPersonInfoPhone" placeholder="请输入联系人电话" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="居住地址" prop="currentResidentialAddress">
              <Cascader @update:address="handleSelectedAdress" v-model="form.currentResidentialAddress" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="户籍地址" prop="registeredResidence">
              <Cascader @update:address="handleSelectedResidence" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />
              是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <!--            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>-->
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script setup name="PatientInfo" lang="ts">
import {
  listPatientInfo,
  getPatientInfo,
  delPatientInfo,
  addPatientInfo,
  updatePatientInfo
} from '@/api/basicPublic/patientInfo';
import {
  HealthRecordVO,
  HealthRecordQuery,
  HealthRecordForm
} from '@/api/basicPublic/patientInfo/healthRecord/HealthRecordTypes';
import { getLabelsByValues, parseTime, AddressConcatenation, getCurrentYearsArray } from '@/utils/ruoyi';
import options from '@/assets/json/address.json';
import { useRouter } from 'vue-router';
import { globalHeaders } from '@/utils/request';
import { DeptVO } from '@/api/system/dept/types';
import api, { listUser } from '@/api/system/user';

const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  bp_pt_sign,
  sys_user_sex,
  bp_complete_status,
  bp_marital_status,
  bp_inspection_type,
  bp_contacts_relationship,
  bp_sign_status,
  bp_inspection_situation
} = toRefs<any>(proxy?.useDict('bp_inspection_situation', 'bp_sign_status', 'bp_contacts_relationship', 'bp_pt_sign', 'sys_user_sex', 'bp_complete_status', 'bp_marital_status', 'bp_inspection_type'));

const patientInfoList = ref<HealthRecordVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);

const total = ref(0);
const deptName = ref('');
const deptOptions = ref<DeptVO[]>([]);
const uploadRef = ref<ElUploadInstance>();
const queryFormRef = ref<ElFormInstance>();
const patientInfoFormRef = ref<ElFormInstance>();
const documentationDateRange = ref([]);
const lastFollowupDateRange = ref([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: HealthRecordForm = {
  id: undefined,
  name: undefined,
  idCard: undefined,
  gender: undefined,
  queueId: 'health_record',
  birthday: undefined,
  maritalStatus: undefined,
  personalPhone: undefined,
  residentialAddress: undefined,
  registeredResidence: {
    province: undefined,//户籍地址-省
    provinceCode: undefined,//户籍地址-省代码
    city: undefined,//户籍地址-市
    cityCode: undefined,//户籍地址-市代码
    area: undefined,//户籍地址-区
    areaCode: undefined,//户籍地址-区代码
    street: undefined,//户籍地址-街道
    streetCode: undefined,//户籍地址-街道代码
    committee: undefined,//户籍地址-社区
    committeeCode: undefined,//户籍地址-社区代码
    detail: undefined//户籍地址-详细地址
  },
  currentResidentialAddress: {
    province: undefined,//户籍地址-省
    provinceCode: undefined,//户籍地址-省代码
    city: undefined,//户籍地址-市
    cityCode: undefined,//户籍地址-市代码
    area: undefined,//户籍地址-区
    areaCode: undefined,//户籍地址-区代码
    street: undefined,//户籍地址-街道
    streetCode: undefined,//户籍地址-街道代码
    committee: undefined,//户籍地址-社区
    committeeCode: undefined,//户籍地址-社区代码
    detail: undefined//户籍地址-详细地址
  },
  isMaternal: undefined,
  isChildren: undefined,
  contact: undefined,
  contactPhone: undefined,
  documentationTime: undefined,
  documentationPeople: undefined,
  dutyDoctor: undefined,
  archiveNumber: undefined,
  documentationUnit: undefined,
  documentationUnitName: undefined,
  contactPersonInfoRelation: undefined,
  contactPersonInfoName: undefined,
  contactPersonInfoPhone: undefined,
  contactPersonInfo: [
    {
      relation: undefined,
      name: undefined,
      phone: undefined
    }
  ]
};
const data = reactive<PageData<HealthRecordForm, HealthRecordQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    idCard: undefined,
    queueInfo: ['health_record'],
    personalPhone: undefined,
    birthday: undefined,
    followupStatus: undefined,
    dutyDoctor: undefined,
    documentationUnit: undefined,
    documentationUnitName: undefined,
    lastInspectionDate: undefined,
    inspectionType: undefined,
    maritalStatus: undefined,
    gender: undefined,
    archiveNumber: undefined,
    documentationStartDate: undefined,
    documentationEndDate: undefined,
    nextFollowupDate: undefined,
    inspectionSituation: undefined,
    documentationPeople: undefined,
    lastFollowupEndDate: undefined,
    lastFollowupStartDate: undefined,
    isSystemIdentification: undefined,
    isInspection: undefined,
    year: undefined,
    params: {},

    range: undefined,
    institution: undefined,
    unanimous: undefined,
    agency: undefined,
    state: undefined,
    documentation: undefined
  },
  rules: {
    // id: [
    //   {required: true, message: "患者id不能为空", trigger: "blur"}
    // ],
    // name: [
    //   {required: true, message: "姓名不能为空", trigger: "blur"}
    // ],
    // idCard: [
    //   {required: true, message: "身份证号不能为空", trigger: "blur"},
    //   {min: 18, max: 18, message: "请输入正确的身份证号", trigger: "blur"}
    // ],
    // gender: [
    //   {required: true, message: "性别不能为空", trigger: "change"}
    // ],
    // birthday: [
    //   {required: true, message: "出生日期不能为空", trigger: "blur"}
    // ],
    // archiveNumber: [
    //   {required: true, message: "档案号不能为空", trigger: "blur"}
    // ],
    // personalPhone: [
    //   {required: true, message: "个人电话不能为空", trigger: "blur"},
    //   {min: 11, max: 11, message: "请输入正确的电话号", trigger: "blur"}
    // ],
    // contactPhone: [
    //   {min: 11, max: 11, message: "请输入正确的手机号", trigger: "blur"}
    // ],
    // currentResidentialAddress: [
    //   {required: true, message: "居住地址不能为空", trigger: "blur"}
    // ],
    // contactPersonInfoPhone: [
    //   {required: true, message: "联系人电话不能为空", trigger: "blur"}
    // ],
    // contactPersonInfoRelation: [
    //   {required: true, message: "联系人关系和电话不能为空", trigger: "blur"}
    // ],
    // contactPersonInfoName: [
    //   {required: true, message: "联系人姓名不能为空", trigger: "blur"}
    // ],
  }
});

/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/basicPublic/patientInfo/importData'
});


const { queryParams, form, rules } = toRefs(data);


const handleSelectedAdress = (value) => {
  form.value.currentResidentialAddress = value;
};


const editQueueInfo = (value) => {
  if (value.length > 1) {
    if (value.indexOf(form.value.queueId) > -1) {
      queryParams.value.queueInfo = value.filter(it => it != form.value.queueId);
    }
  } else if (value.length == 1 && value.indexOf(form.value.queueId) == -1) {
    queryParams.value.queueInfo = value;
  } else {
    queryParams.value.queueInfo = [form.value.queueId];
  }
};


const handleSelectedResidence = (value) => {
  form.value.registeredResidence = value;
};


/** 获取医生字典 */
const doctorDictList = ref<any[]>([]);
const doctorDictLists = ref<any[]>([]);

const getDoctorDictList = async () => {
  const res = await listUser();
  console.log('获取医生字典', res);
  doctorDictList.value = res.rows;
  doctorDictLists.value = doctorDictList.value.map(it => ({
    elTagClass: '',
    elTagType: '',
    label: it.nickName,
    value: String(it.userId)
  }));
};


/** 查询患者基本信息列表 */
const getList = async () => {
  loading.value = true;

  setDateRange(documentationDateRange.value, 'documentationStartDate', 'documentationEndDate', 'params');

  if ((queryParams.value.isInspection || queryParams.value.isSystemIdentification) && !queryParams.value.year) {
    proxy?.$modal.msgWarning('是否健康体检、是否中医体质辨识必须关联年份查询，请选择年份！');
    loading.value = false;
    return;
  }
  // if (!queryParams.value.documentationUnit) {
  //   proxy?.$modal.msgWarning("请选择部门");
  //   loading.value = false;
  //   return;
  // }

  const res = await listPatientInfo(queryParams.value);
  // patientInfoList.value = res.rows as HealthRecordVO[];
  patientInfoList.value = res.rows as HealthRecordVO[];
  total.value = res.total;
  // console.log('查询患者基本信息列表',patientInfoList.value)
  loading.value = false;
};


const setDateRange = (dateRange, startDateKey, endDateKey, pin) => {
  if (dateRange) {
    queryParams.value[pin][startDateKey] = parseTime(dateRange[0]);
    queryParams.value[pin][endDateKey] = parseTime(dateRange[1]);
  } else {
    queryParams.value[pin][startDateKey] = undefined;
    queryParams.value[pin][endDateKey] = undefined;
  }
};


/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  queryParams.value.idCard = undefined;
};


/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
};


/** 节点单击事件 */
const handleNodeClick = (data: DeptVO) => {
  queryParams.value.documentationUnit = data.id;
  handleQuery();
};


/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};


const doctorDictListForm = ref<any[]>([]);

async function handleDeptChange(value: number | string) {
  const can = {
    deptId: value
  };
  const res = await listUser(can);
  console.log('111', res);
  doctorDictListForm.value = res.rows;
}


/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  patientInfoFormRef.value?.resetFields();
};


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  lastFollowupDateRange.value = undefined;
  documentationDateRange.value = undefined;
  handleQuery();
};

/** 重置按钮操作 */
const resetQuerys = () => {
  reset();
  queryParams.value.idCard = undefined;
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: HealthRecordVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加健康档案基本信息';
};


/** 查看按钮操作 */

const handleLook = (row?: HealthRecordVO) => {
  // console.log($router)
  router.push({
    path: '/workBenches/workBenches',
    query: {
      id: row?.id
    }
  });
};


/** 提交按钮 */
const submitForm = () => {
  patientInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.contactPersonInfo = [
        {
          relation: undefined,
          name: undefined,
          phone: undefined
        }
      ];
      form.value.contactPersonInfo[0].relation = form.value.contactPersonInfoRelation;
      form.value.contactPersonInfo[0].name = form.value.contactPersonInfoName;
      form.value.contactPersonInfo[0].phone = form.value.contactPersonInfoPhone;
      await addPatientInfo(form.value).finally(() => buttonLoading.value = false);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
    }
  });
};


/** 删除按钮操作 */
const handleDelete = async (row?: HealthRecordVO) => {
  const _ids = row?.id || ids.value;
  const _name = row?.name;
  await proxy?.$modal.confirm('是否确认删除患者"' + _name + '"的基本信息？').finally(() => loading.value = false);
  await delPatientInfo(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('basicPublic/patientInfo/export', {
    ...queryParams.value
  }, `patientInfo_${new Date().getTime()}.xlsx`);
};

/** 打开导入表弹窗 */
/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '患者信息导入';
  upload.open = true;
};
/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`);
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}


const handleChange = (value) => {
  console.log(getLabelsByValues(value, options));
};


onMounted(() => {
  getTreeSelect();
  getDoctorDictList();
  // getList();
});

</script>
<style scoped lang="scss">
::v-deep .el-cascader {
  .el-input {
    //width: 300px;
  }
}
</style>
